package com.tph.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.tph.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @ClassName TokenFilter
 * @Description 实现未登录拦截
 * @Author LiHao
 * @Date 2022/12/27 19:25
 * @Version 1.0
 */

//@Component
public class TokenFilter implements GlobalFilter {
    private final Logger logger = LoggerFactory.getLogger(TokenFilter.class);
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取当前的请求路径
        ServerHttpRequest request = exchange.getRequest();
        String url = request.getPath().toString();
        logger.info(url);
        if (checkUrl(url)) {
            return chain.filter(exchange);
        } else {
            //需要拦截校验如果没有令牌就拦截，并返回错误信息，有令牌则放行
            List<String> tokens = request.getHeaders().get("token");
            logger.info("tokens-->"+tokens);
            if (tokens != null && tokens.size() > 0) {
                return chain.filter(exchange);
            }
        }
        //拦截请求 并返回结果
        ServerHttpResponse response = exchange.getResponse();
        //设置响应的内容的格式 json
        response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
        return response.writeWith(
                Mono.just(response.bufferFactory().
                        wrap(JSON.toJSONString(R.fail("亲，令牌失效，请重新登录！")).getBytes())));
    }

    private boolean checkUrl(String url) {
        return url.contains("login.do") || url.contains("register.do") || url.contains(".html") || url.contains(".css") || url.contains(".js") || url.contains("v3/api-docs") || url.contains("swagger-resources");
    }
}
